package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptios.LyException;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static final String DEDUCT_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.deductStock";
    private static final String ADD_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.addStock";

    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> cartMap) {
        try {
            updateStock(cartMap, DEDUCT_STOCK_STATEMENT);
        } catch (Exception e) {
            throw new LyException(400, "库存不足", e);
        }
    }

    @Override
    @Transactional
    public void addStock(Map<Long, Integer> cartMap) {
        updateStock(cartMap, ADD_STOCK_STATEMENT);
    }

    private void updateStock(Map<Long, Integer> cartMap, String statement) {
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                // 准备参数
                Map<String, Object> param = new HashMap<>();
                param.put("id", entry.getKey());
                param.put("num", entry.getValue());
                // 编译statement，namespace.statementId
                sqlSession.update(statement, param);
                // 刷新
                sqlSession.flushStatements();
            }
        });
    }
}
